<?php

namespace App\Jobs;

use App\Http\Service\DeviceService;
use App\Model\Device;
use App\Model\DeviceBus;
use App\Model\DeviceBuslog;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;


class CheckMainReduce implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $logId;
    public $tries = 2;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function  __construct($logId)
    {

        $this->logId = $logId;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $log = DeviceBuslog::query()->where('id',$this->logId)->first();
        $device =  Device::query()->where('id',$log->main_device_id)->first();
        if(empty($device)){
            $log->status = 3;
            $log->save();
            return '';
        }
        if($device->du >= $log->main_du){
            $log->status = 3;
            $log->save();
        }else{
            $log->status = 1;
            $log->save();
            $busInfo = DeviceBus::query()->where('device_id',$device->id)->where('type',1)->first();
            $memInfo =  DeviceBus::query()->where('pid',$busInfo->id)
                ->where('status',1)
                ->get();
            $service = app()->make(DeviceService::class);
            foreach($memInfo as $k => $mem){
                try{
                    $du = number_format(($log->main_du*$mem->rate)/100,2,'.','');
                    if($du > 0){
                        $slog = new DeviceBuslog();
                        $slog->log_id = $log->id;
                        $slog->main_device_id = $busInfo->device_id;
                        $slog->mem_device_id = $mem->device_id;
                        $slog->main_du = $log->main_du;
                        $slog->du = $du;
                        $slog->rate = $mem->rate;
                        $memDevice = Device::query()->where('id',$mem->device_id)
                            ->first();
                        $slog->mac =$memDevice->mac;
                        $slog->mem_du = $memDevice->du;
                        $slog->type = 2;
                        $slog->save();
                        $service->editDu($memDevice->mac,$du);
                        dispatch(new CheckReduce($slog->id))->delay(30);
                    }
                }catch (\Exception $e){
                    Log::info($e->getMessage());
                }
            }
        }
    }
}

